# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models, _


import logging
_logger = logging.getLogger(__name__)

class AccountJournal(models.Model):
    _inherit = "account.journal"

    internal_code = fields.Char(string='Long Code', default='odoo' )


class AccountChartTemplate(models.Model):
    """
    安装科目模版时, 要设置科目, 因此所有的默认科目必须在这里定义
    """
    
    _inherit = "account.chart.template"

    property_account_profit_id = fields.Many2one('account.account.template', string='Profit Account')
    property_account_vat_income_id = fields.Many2one('account.account.template', string='VAT Income Account')
    property_account_vat_expense_id = fields.Many2one('account.account.template', string='VAT Expense Account')
    property_account_tax_expense_id = fields.Many2one('account.account.template', string='Tax Expense Account')
    property_account_material_id = fields.Many2one('account.account.template', string='Raw Material Account')
    property_account_goods_id = fields.Many2one('account.account.template', string='Stock Goods Account')
    property_account_production_id = fields.Many2one('account.account.template', string='Production Account')
    property_account_inventory_material_id = fields.Many2one('account.account.template', string='Inventory Material Account')
    property_account_inventory_goods_id = fields.Many2one('account.account.template', string='Inventory Goods Account')
    property_account_salary_id = fields.Many2one('account.account.template', string='Salary Account')
    property_account_salary_tax_id = fields.Many2one('account.account.template', string='Salary Tax Account')
    property_account_other_payable_id = fields.Many2one('account.account.template', string='Other Payable Account')
    

class AccountAccount(models.Model):
    _inherit = 'account.account'
    
    general_code = fields.Char( store=True,compute='_compute_general' )
    general_name = fields.Char( store=True,compute='_compute_general' )

    #tag_ids = fields.Many2many('account.account.tag', 'account_account_account_tag', string='Tags', help="Optional tags you may want to assign for custom reporting")
        
    sub_type = fields.Selection([
        ('none', 'None'), 
        ('bank', 'Bank'), 
        ('partner', 'Partner'), 
        ('product', 'Product'), 
        ('analytic', 'Analytic'),
        #('tag', 'Analytic Tag'), 
    ], store=True, compute='_compute_sub_type' )

    @api.depends('tag_ids')
    def _compute_sub_type(self):
        for line in self:
            detail_tag_id = line.tag_ids.filtered(lambda tag: tag.type == 'detail')
            detail_tag_id = detail_tag_id and detail_tag_id[0]
            code = detail_tag_id.code
            code = code in [
                'bank','partner','product','analytic',
                #'tag'
            ] and code or 'none'
            
            line.sub_type = code
    
    @api.depends('code')
    def _compute_general(self):
        for line in self:
            code = line.code[0:4] 
            line.general_code = code
            code0 = '00'
            if code in ['1001','1002']:
                code0 = '01'
            elif code in ['9999']:
                code0 = '99'
            
            code = code + code0
            line.general_name = self.search([('code','=',code)], limit=1).name

    @api.model
    def create(self, vals):
        account = super(AccountAccount,self).create(vals)
        if len(account.code) == 6 and account.code[4:6] == '00':
            code = account.code[0:4] 
            for acc in self.search([('general_code','=',code)]):
                acc.general_name = account.name
        
        account._set_tags()
        return account


    def _set_tags(self):
        tag_ids = self.env['account.account.tag']
        tags = self.env['account.account.tag'].search([])
        
        for tag in tags:
            codes = ( tag.account_codes and tag.account_codes.split(',') or [] )
            
            if self.code in [
                c for cs in [
                    len(code)==4 and [code + '00',code + '01', code + '99'] or [code] 
                    for code in codes
                ] for c in cs 
            ]:
                tag_ids += tag
        
        self.tag_ids = tag_ids

class ProductProduct(models.Model):
    _inherit = "product.product"

    @api.multi
    def write(self, values):
        res = super(ProductProduct, self).write(values)
        
        if 'name' in values:
            self.product_tmpl_id.name = values['name']
            
        return res

"""
class AccountAnalyticTag(models.Model):
    _inherit = 'account.analytic.tag'
    
    # For detail account
    type = fields.Selection([
        ('odoo', 'Odoo'), 
        ('detail', 'Detail Account')
    ], required=True, default='odoo', help='User for report')
    
    code = fields.Char()
"""    
    

class AccountAccountTag(models.Model):
    _inherit = 'account.account.tag'

    # _inherit from
    #name = fields.Char(required=True)
    #applicability = fields.Selection([('accounts', 'Accounts'), ('taxes', 'Taxes')], required=True, default='accounts')
    #color = fields.Integer('Color Index')
    #active = fields.Boolean(default=True, help="Set active to false to hide the Account Tag without removing it.")

    code = fields.Char()

    type = fields.Selection([
        ('odoo', 'Odoo'), 
        ('balance', 'Balance Sheet'), 
        ('profit', 'Profit Sheet'), 
        ('detail', 'Detail Account')
    ], required=True, default='odoo', help='User for report')
    
    account_codes = fields.Char()

    account_ids = fields.Many2many('account.account','account_account_account_tag',string='Accounts')
    
    group_num = fields.Integer(store=True,compute='_compute_code')
    code4 = fields.Char(store=True,compute='_compute_code')
    sign = fields.Integer(store=True,compute='_compute_code')
    is_age = fields.Integer(store=True,compute='_compute_code')
    gt_one_year = fields.Integer(store=True,compute='_compute_code')

    @api.depends('code')
    def _compute_code(self):
        for line in self:
            if line.type in ['balance','profit']:
                [group_num, code4, sign, is_age, gt_one_year] = line.code.split(',')
                line.group_num = int(group_num)
                line.code4 = code4
                line.sign = int(sign)
                line.is_age = int(is_age)
                line.gt_one_year = int(gt_one_year)
